// src/store/user.ts
import { defineStore } from 'pinia'
import { loginApi, getUserInfoApi, logoutApi } from '@/api/user'
import type { LoginForm } from '@/api/types'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 从 localStorage 读取 token，实现持久化
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
  }),
  getters: {
    isLoggedIn: (state) => !!state.token,
  },
  actions: {
    // 用户登录
    async login(loginForm: LoginForm) {
      try {
        // 调用登录 API
        const data = await loginApi(loginForm)
        // 根据 API 文档，data 包含 { token, user }
        this.token = data.token
        this.userInfo = data.user
        // 持久化存储
        localStorage.setItem('token', this.token)
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        return Promise.resolve()
      } catch (error) {
        return Promise.reject(error)
      }
    },

    // 获取用户信息
    async fetchUserInfo() {
      try {
        const data = await getUserInfoApi();
        this.userInfo = data;
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo));
      } catch(error) {
        // 如果获取失败（例如 token 失效），则清空信息
        this.resetUser()
        return Promise.reject(error)
      }
    },

    // 用户登出
    async logout() {
      try {
        await logoutApi() // 通知后端登出
      } catch (error) {
        console.error("Logout API failed, but clearing local data anyway.", error)
      } finally {
        this.resetUser()
      }
    },

    // 重置用户信息和 token
    resetUser() {
        this.token = ''
        this.userInfo = {}
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
    }
  },
})